import axios from 'axios';

// HTTP工具类
export default class base {
    static request (method, url, data, all = false) {
        const param = {
            url: url,
            method: method,
            params: data,
            data: data
        };
        console.log(`[http]request url=${url}`);

        return axios(param).then(res => {
            if (this.isSuccess(res)) {
                // console.log(res.data);
                return all ? res.data : res.data.data;
            } else {
                throw this.requestException(res);
            }
        });
    }

    /**
* 判断请求是否成功
*/
    static isSuccess (res) {
    // console.log(res, 'isSuccess');
        const respCode = res.status;
        // 微信请求错误
        if (respCode !== 200) {
            return false;
        }
        const respData = res.data;
        return !(respData && respData.code !== 0);
    }

    /**
* 异常
*/
    static requestException (res) {
        const error = {};
        error.status = res.status;
        const respData = res.data;
        if (respData) {
            error.title = '错误信息';
            error.serverCode = respData.code;
            error.message = respData.msg;
            error.serverData = respData;
        }

        return error;
    }

    static get (url, data, all = false) {
        return this.request('GET', url, data, all);
    }

    static put (url, data, all = false) {
        return this.request('PUT', url, data, all);
    }

    static post (url, data, all = false) {
        return this.request('POST', url, data, all);
    }

    static patch (url, data, all = false) {
        return this.request('PATCH', url, data, all);
    }

    static delete (url, data, all = false) {
        return this.request('DELETE', url, data, all);
    }
}
